<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessage } from 'element-plus'
import { Table } from '@/components/Table'
import { getListApi, deleteDataApi, getFieldEnumApi } from '@/api/logisticsRules'
import { CurdData, FieldEnum } from '@/api/logisticsRules/types'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref } from 'vue'
import { useRouter } from 'vue-router'
import { useEventBus } from '@/hooks/event/useEventBus'
import { useCrudSchemas, AllSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { ActionButtonsTemplate, SchemaConfig } from '@/api/global/types'
import useSchema from './components/hooks/useSchema'

defineOptions({
  name: 'CompanyPage'
})

const { push } = useRouter()

const ids = ref<string[]>([])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListApi({
      page: unref(currentPage),
      pagesize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    // const res = await deleteDataApi(unref(ids))
    const res = await deleteDataApi(unref(ids).join(','))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

getList()

useEventBus({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})

const { t } = useI18n()

// Begin CRUD Template Block
// ------------------------
const delLoading = ref(false)

const delData = async (row: CurdData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: CurdData) => v.id) || []
  console.log(ids.value)
  if (ids.value.length === 0) {
    ElMessage.error(t('common.selectData'))
    return
  }
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: CurdData, type: string) => {
  push(`/logistics/rules/${type}?id=${row.id}`)
}

const actionButtonsTemplate: ActionButtonsTemplate = {
  length: 3,
  template: (data: any) => {
    return (
      <>
        <BaseButton size="small" onClick={() => action(data.row, 'edit')}>
          {t('action.edit')}
        </BaseButton>
        <BaseButton size="small" type="success" onClick={() => action(data.row, 'detail')}>
          {t('action.detail')}
        </BaseButton>
        <BaseButton size="small" type="danger" onClick={() => delData(data.row)}>
          {t('action.del')}
        </BaseButton>
      </>
    )
  }
}

const allSchemas = ref<AllSchemas>({
  searchSchema: [], // 确保与接口匹配
  tableColumns: [] // 确保与接口匹配
})
const fieldEnum = ref<FieldEnum>({}) // 根据实际数据初始化
getFieldEnumApi({ field: 'all' })
  .then((res) => {
    fieldEnum.value = res.data
    const schemaConfig: SchemaConfig = {
      actionButtonsTemplate,
      fieldEnum: fieldEnum.value
    }

    const { crudSchemas } = useSchema(schemaConfig)
    const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

    // 合并新的数据，确保不改变原有数据的类型
    allSchemas.value = {
      searchSchema: newSchemas.searchSchema || [],
      tableColumns: newSchemas.tableColumns || []
    }
  })
  .catch((error) => {
    console.error('API call failed', error)
  })

// End CRUD Template Block
// ------------------------

const AddAction = () => {
  push('/logistics/rules/add')
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('action.add') }}</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('action.del') }}
      </BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
@/hooks/event/useEventBus
